package com.sun.audit.resolver;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sun.corba.se.spi.ior.Identifiable;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
public class EntityIdResolver {
    public static Long resolve(Class<?> entityClass, Object param) throws NoSuchFieldException, IllegalAccessException {
        // 1. 优先从实体对象获取ID
        if (entityClass.isInstance(param)) {
            return extractIdFromEntity(param);
        }

        // 2. 处理MyBatis-Plus的UpdateWrapper
//        if (param instanceof UpdateWrapper) {
//            UpdateWrapper<?> wrapper = (UpdateWrapper<?>) param;
//            Object entity = wrapper.getEntity();
//            if (entity != null) {
//                return extractIdFromEntity(entity);
//            }
//            // 从WHERE条件提取ID (e.g. eq("id", 123))
//            return extractIdFromWrapper(wrapper);
//        }

        // 3. 处理@Param注解参数
        if (param instanceof Map) {
            Map<?, ?> paramMap = (Map<?, ?>) param;
            log.info("paramMap: {}", paramMap);
//            // 尝试常见ID参数名
//            for (String key : Arrays.asList("id", "eid", "entityId", "key")) {
//                Object idObj = paramMap.get(key);
//                if (idObj instanceof Long) {
//                    return (Long) idObj;
//                }
//            }
            for (Object value : paramMap.keySet()) {
                String key = value.toString();
                if (key.equals("et")) {
                    Object entityParam = paramMap.get(key);
                    log.info("entityParam: {}", entityParam);
                    if (entityParam != null) {
                        Field idField = entityParam.getClass().getDeclaredField("id");
                        idField.setAccessible(true); // 设置可访问，即使是private字段
                        Object idValue = idField.get(entityParam);
                        if (idValue instanceof Long) {
                            return (Long) idValue;
                        } else if (idValue instanceof Number) {
                            // 如果是其他数字类型，转换为Long
                            return ((Number) idValue).longValue();
                        }
                    }
                }
            }
            // 尝试获取实体对象
            for (Object value : paramMap.values()) {
                if (entityClass.isInstance(value)) {
                    return extractIdFromEntity(value);
                }
            }
        }

        return null;
    }

    private static Long extractIdFromEntity(Object entity) {
        try {
            // 兼容多种ID获取方式
            if (entity instanceof Identifiable) {
                return (long) ((Identifiable) entity).getId();
            }

            Method getId = entity.getClass().getMethod("getId");
            if (getId.getReturnType() == Long.class) {
                return (Long) getId.invoke(entity);
            }

            Field idField = entity.getClass().getDeclaredField("id");
            idField.setAccessible(true);
            return (Long) idField.get(entity);
        } catch (Exception e) {
            return null;
        }
    }

    private static Long extractIdFromWrapper(UpdateWrapper<?> wrapper) {
//        List<Object> idValues = wrapper.allEq().values().stream()
//                .filter(obj -> "id".equals(obj.getColumn()))
//                .map(obj -> obj.getValue())
//                .collect(Collectors.toList());

//        return idValues.isEmpty() ? null : (Long) idValues.get(0);
        return null;
    }
}
